var JSmile=JSmile||{};
/*
 * 定义全局js常量
 */	
JSmile.KConfig={
	getRootPath:function(){//获取项目地址
	    //获取当前网址，如： http://localhost:8083/share/index.jsp
	    var curWwwPath=window.document.location.href;
	    //获取主机地址之后的目录，如： /share/meun.jsp
	    var pathName=window.document.location.pathname;
	    var pos=curWwwPath.indexOf(pathName);
	    //获取主机地址，如： http://localhost:8083
	    var localhostPaht=curWwwPath.substring(0,pos);
	    //获取带"/"的项目名，如：/share
	    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
	    return (localhostPaht + projectName);
	}
};
/*
 * 项目名称
 */
JSmile.baseUrl= JSmile.KConfig.getRootPath();
JSmile.KStatus={
	initStatus:function(value,row,index){
		  if(value==1||value=='1'){
				return "<div style=\"background-color:#5cb85c;width:60%;color:white;margin:0 auto;\">正常</div>";
			}else{
				return "<div style=\"background-color:#d9534f;width:60%;color:white;margin:0 auto;\">禁用</div>";
			}
	}
};
/*
 * easyui扩展工具类
 */
JSmile.KHttp={
		send:function(options){
			var settings={
				async:true,
				dataType:"json",
				contentType:"application/x-www-form-urlencoded",
				type:"post"
			};
			for(var i in options){
				settings[i] = options[i] || settings[i];
			}
			settings.url=JSmile.baseUrl+settings.url;
			return $.ajax(settings).then(function(res){
				if('ok'==res.resState){
					return res;
				}else{
					top.$.messager.alert("提示", !res.resMsg?"请求失败!":res.resMsg, "info");  
					return $.Deferred().reject(res); 
				}
			},function(err){
				top.$.messager.alert("提示", "数据加载失败!", "info");  
			});
		}		
};
/*
 * ajax封装实现
 */
JSmile.KEasy={
	edit:function(_selRows,_func){
		if(_selRows.length==0){
			$.messager.alert("提示", "请选择其中的一行！", "info");  
			return;
		}else if(_selRows.length==1){
			_func();
		}else{
			$.messager.alert("提示", "只能选择其中一行进行修改!", "info");
		}
	},	
  del:function(_url,selRows,_func){
    	if(selRows.length==0){
    		$.messager.alert("提示", "请选择要删除的行!", "info");  
    		return;
    	}else{
    		var ids=[];  
            //批量获取选中行的ID  
            for (i = 0; i < selRows.length;i++) {  
            	ids.push(selRows[i]['id']);               
            }  
            $.messager.confirm('提示', '是否删除选中数据,?', function (r) {  
                if (!r) {  
                    return;  
                }  
                JSmile.KHttp.send({url:_url,data:{"ids":ids}}).done(function(res){
                	_func(res);
                });
            });
    	}
    },
	initForm:function(_id,_url,_func){
		if(JSmile.Kit.isBlank(_url)){
			$.messager.alert("提示", "请求url不能为空!", "info");  
			return;
		}
		return $(_id).form({
			url:JSmile.baseUrl+_url,
		    onSubmit: function(){    
                var isValid =true;
                if(JSmile.Kit.isFunction(_func)){
                	isValid=_func();
                }
                if(!isValid){
                	return false;
                }
                progressLoad();
                isValid = $(this).form('validate');
                if (!isValid) {
                    progressClose();
                }
                return isValid;
		    },
		    success: function(data){
                progressClose();
                data = $.parseJSON(data);
                if ('ok'==data.resState) {
                	if(top.$.modalDialog.open_datagrid){
                		top.$.modalDialog.open_datagrid.datagrid('clearSelections').datagrid('clearChecked').datagrid('reload');//之所以能在这里调用到parent.$.modalDialog.openner_dataGrid这个对象，是因为user.jsp页面预定义好了
                	}
                	if(top.$.modalDialog.open_treegrid){
                		top.$.modalDialog.open_treegrid.treegrid('clearSelections').treegrid('clearChecked').treegrid('reload');//之所以能在这里调用到parent.$.modalDialog.openner_dataGrid这个对象，是因为user.jsp页面预定义好了
                	}
                	if(JSmile.Kit.isFunction(top.$.modalDialog.submitSuccess)){
                		top.$.modalDialog.submitSuccess(data);
                	}
                	top.$.messager.alert("提示", !data.resMsg?"请求成功!":data.resMsg, "info"); 
                    top.$.modalDialog.handler.dialog('close');
                } else {
                	top.$.messager.alert('提示', !data.resMsg?"请求失败!":data.resMsg, 'info');
                }
		    }
		});
	},
    /*
     * 统一错误处理
     */
	doError:function(data,func){
		if(JSmile.Kit.isString(data)){
			data= $.parseJSON(data); 
		}
		if('ok'==res.resState){
		   if(JSmile.Kit.isFunction(func)){
				 func(data);
		   }
		}else {
			top.$.messager.alert("提示", !data.resMsg?"请求失败!":data.resMsg, "error"); 
		}
	},
	initDatagrid:function(options){
		if(JSmile.Kit.isBlank(options.url)){
			$.messager.alert("提示", "请求url不能为空!", "info");  
			return;
		}
    	/**
    	 * 初始化treegrid，必须传参数
    	 * url请求地址
    	 */
		var settings = {
				autoRowHeight:true,
				fitColumns:true,
				striped:true,
				nowrap:true,
				singleSelect:false,
				method:'POST',
				pagination: true,
				pageSize:10,
				pageList: [10,20,50,100],
				pagePosition:'bottom',
				checkOnSelect:true,
				selectOnCheck:true,
				collapsible: true,
				queryParams:{},
				fit : true,
				remoteSort:false,
				multiSort:true,
				idField:'id',
			    onLoadSuccess:function(){
					 $(this).datagrid('tooltip');
				}
			};
			for(var i in options){
				settings[i] = options[i] || settings[i];
			}
			settings.url=JSmile.baseUrl+settings.url;
			return settings;
	},
	/**
	 * 初始化treegrid，必须传参数
	 * url请求地址
	 */
	initTreegrid:function(options){
		if(JSmile.Kit.isBlank(options.url)){
			$.messager.alert("提示", "请求url不能为空!", "info");  
			return;
		}
		var settings = {
			autoRowHeight:true,
			fitColumns:true,
			striped:true,
			nowrap:true,
			singleSelect:true,
			method:'POST',
			pageSize:20,
			pageList: [10,20,50,100],
			checkOnSelect:true,
			selectOnCheck:true,
			collapsible: true,
			queryParams:{},
			fit : true,
			remoteSort:false,
			multiSort:true,
			idField:'id',
			treeField:'name',
		    onLoadSuccess:function(){
				 $(this).treegrid('tooltip');
			}
			};
			for(var i in options){
				settings[i] = options[i] || settings[i];
			}
			settings.url=JSmile.baseUrl+settings.url;
			return settings;
	}		
};
/*
 * js工具集合
 */
JSmile.Kit={
	formatString:function(str){
	    for ( var i = 0; i < arguments.length - 1; i++) {
	        str = str.replace("{" + i + "}", arguments[i + 1]);
	    }
	    return str;
	},	
    isString:function(str){
    	return (typeof str=='string')&&str.constructor==String; 
    },		
    isArray:function(obj){
    	return (typeof obj=='object')&&obj.constructor==Array; 
    },
    isObject:function(obj){
    	return (typeof obj=='object')&&obj.constructor==Object; 
    },
    isFunction:function(obj){
    	return (typeof obj=='function')&&obj.constructor==Function; 
    },
	getQueryString:function(sProp){//获取页面传来的值
	    var re = new RegExp("[&,?]"+sProp + "=([^//&]*)", "i");  
	    var a = re.exec(document.location.search);  
	    if (a == null)  
	        return "";  
	    return a[1]; 
	},
	paresURI:function(){//解析uri传来的参数为json
		   var patten=/([-\w]+)=([\w,%]+)/ig;
		   var parames = {};
		   document.location.search.replace(patten, function(a, b, c){
		       parames[b] = c;
		   });
		   return parames;
	},
	browser:function(){//true 为移动端,false为pc端
	    var sUserAgent = navigator.userAgent.toLowerCase();
	    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
	    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
	    var bIsMidp = sUserAgent.match(/midp/i) == "midp";
	    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
	    var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
	    var bIsAndroid = sUserAgent.match(/android/i) == "android";
	    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
	    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
	    if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
	        document.writeln("phone");
	    } else {
	        document.writeln("pc");
	    }
	    return bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM;
	},
	isBlank:function(value){
		if(value==null||value==undefined||String(value).replace(/(^\s*)|(\s*$)/g,"").length<=0){
			return true;
		}
		if(typeof(value)=="object"){
			 for (var item in value){
				 return false;
			 }
			 return true;
		}
	},
	isNotBlank:function(value){
		var _this=this;
		return !_this.isBlank(value);
	},
	isUserName: function (str) {//  验证是否可以作为合法的用户名字符(字母开头，允许6-16字节，允许字母数字下划线)
		var _this=this;
		str = _this.isBlank(str) ? "" : String(str);
	    return /^[a-zA-Z]{1}[0-9a-zA-Z_]{3,15}$/i.test(str);
	},
	isIDCard : function (str) {//  判断当前 String 对象是否是正确的 身份证号码(中国) 格式。
		var _this=this;
		str = _this.isBlank(str) ? "" : String(str);
	    var iSum = 0,
	        sId = str,
	        aCity = {
	            11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古",
	            21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏",
	            33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东",
	            41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西",
	            46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南",
	            54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏",
	            65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外"
	        };
	    if (!/^\d{17}(\d|x)$/i.test(sId)) {
	        return false;
	    }
	    sId = sId.replace(/x$/i, "a");
	    //非法地区
	    if (aCity[parseInt(sId.substr(0, 2), 10)] == null) {
	        return false;
	    }
	    var sBirthday = sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2)),
	        d = new Date(sBirthday.replace(/-/g, "/"));
	    //非法生日
	    if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate())) {
	        return false;
	    }
	    for (var i = 17; i >= 0; i--) {
	        iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
	    }
	    if (iSum % 11 != 1) {
	        return false;
	    }
	    return true;
	},
	isTel : function (str) {//  判断当前 String 对象是否是正确的电话号码格式(中国)。
		var _this=this;
	    str = _this.isBlank(str) ? "" : String(str);
	    return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(str);
	},
	isMobile : function (str) {//  判断当前 String 对象是否是正确的手机号码格式(中国)。
		var _this=this;
		str = _this.isBlank(str) ? "" : String(str);
	    return /^(13|14|15|17|18)\d{9}$/i.test(str);
	},
	isTelOrMobile : function (str) {//  判断当前 String 对象是否是正确的电话号码或者手机号码格式(中国)
		var _this=this;
		return _this.isTel(str) || _this.isMobile(str);
	},

	isZipCode : function (str) {//  判断当前 String 对象是否是正确的 邮政编码(中国) 格式。
		var _this=this;
		str = _this.isBlank(str) ? "" : String(str);
	    return /^[\d]{6}$/.test(str);
	},
	existChinese: function (str) {//  判断当前 String 对象是否是否存在汉字字符。
		var _this=this;
		str = _this.isBlank(str) ? "" : String(str);
	    //[\u4E00-\u9FA5]為漢字﹐[\uFE30-\uFFA0]為全角符號
	    return !/^[\x00-\xff]*$/.test(str);
	},

	isChinese: function (str) {//  验证中文
		var _this=this;
		str = _this.isBlank(str) ? "" : String(str);
	    return /^[\u0391-\uFFE5]+$/i.test(str);
	},
	isEnglish : function (str) {//  验证英文
		var _this=this;
		str = _this.isBlank(str) ? "" : String(str);
	    return /^[A-Za-z]+$/i.test(str);
	},
	isNumber:function(value){
		var reg =/^[0-9]*$/;  
        return reg.test(value);  
	},
	isEmail : function (str) {//判断当前 String 对象是否是正确的 电子邮箱地址(Email) 格式。
		var _this=this;
		str = _this.isBlank(str) ? "" : String(str);
	    return str.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1;
	},
	stringToList: function(value) {//接收一个以逗号分割的字符串，返回List，list里每一项都是一个字符串
	    if (value != undefined && value != '') {
	        var values = [];
	        var t = value.split(',');
	        for ( var i = 0; i < t.length; i++) {
	            values.push('' + t[i]);/* 避免他将ID当成数字 */
	        }
	        return values;
	    } else {
	        return [];
	    }
	}
};
/**
 * 树形控件的优化
 */
JSmile.convert=function(rows,opt){
    if(rows.resData.rows){
    	rows= rows.resData.rows;
    }
    opt=opt||{};
	var idField=opt.idField || 'id',
	textField=opt.textField || 'name',
	lv=opt.level||88,
	parentField= opt.parentField||"parentId";
	var nodes = [];
	// get the top level nodes
	for(var i=0; i<rows.length; i++){
		var row = rows[i];
		if (row[parentField]==null||row[parentField]==0){
			var n=jQuery.extend(true, {}, row);
			n.id=row[idField];
			n.text=row[textField];
            if(!n.attributes){
            	n.attributes={level:1};
            }else{
            	n.attributes.level=1;
            }
			nodes.push(n);
		}
	}
	var toDo = [];
	for(var i=0; i<nodes.length; i++){
		toDo.push(nodes[i]);
	}
	while(toDo.length){
		var node = toDo.shift();	// the parent node
		var isLeaf=false;
		// get the children nodes
		for(var i=0; i<rows.length; i++){
			var row = rows[i];
			if(node.attributes.level!=lv){
				if (row[parentField] == node[idField]){
					var child=jQuery.extend(true, {}, row);
                    child.id=row[idField];
                    child.text=row[textField];
                    if(!child.attributes){
                    	child.attributes={level:node.attributes.level+1};
                    }else{
                    	child.attributes.level=node.attributes.level+1;
                    }
					if (node.children){
						node.children.push(child);
					} else {
						node.children = [child];
					}
					toDo.push(child);
					node.state='closed';
					isLeaf=true;
				}
			}
		}
		if(!isLeaf){
			node.state='open';
		}
	}
	return nodes;
};
JSmile.convertTreegrid=function(rows,opt){
    if(rows.resData.rows){
    	rows= rows.resData.rows;
    }
    opt=opt||{};
	var idField=opt.idField || 'id',
	textField=opt.textField || 'name',
	lv=opt.level||88,
	parentValue=opt.parentValue||null,
	parentField= opt.parentField||"parentId";
	var nodes = [];
	// get the top level nodes
	for(var i=0; i<rows.length; i++){
		var row = rows[i];
		if (row[parentField]==null||row[parentField]==0||row[parentField]==parentValue){
			var n={};
			for(var tem in row){
				n[tem]=row[tem];
				if(tem===idField){
					n.id=row[tem];
				}
				if(tem===textField){
					n.text=row[tem];
				}
                if(!row.level){
                	n.level=1;
                }else{
                	n.level=row.level;
                }
			}
			nodes.push(n);
		}
	}
	var toDo = [];
	for(var i=0; i<nodes.length; i++){
		toDo.push(nodes[i]);
	}
	while(toDo.length){
		var node = toDo.shift();	// the parent node
		var isLeaf=false;
		// get the children nodes
		for(var i=0; i<rows.length; i++){
			var row = rows[i];
			if(node.level!=lv){
				if (row[parentField] == node[idField]){
					var child={};
					for(var tem in row){
						child[tem]=row[tem];
						if(tem===idField){
							child.id=row[tem];
						}
						if(tem===textField){
							child.text=row[tem];
						}
						child.level=node.level+1;
					}
					if (node.children){
						node.children.push(child);
					} else {
						node.children = [child];
					}
					toDo.push(child);
					node.state='closed';
					isLeaf=true;
				}
			}
		}
		if(!isLeaf){
			node.state='open';
		}
	}
	return nodes;
};